package xyz.longicorn.driver.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaFilterErrorStrategy;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.router.SaHttpMethod;
import cn.dev33.satoken.router.SaRouter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import xyz.longicorn.driver.dto.ApiResult;

// 主要处理sa-token的拦截和跨域问题
@Configuration
public class SaTokenConfig {
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .addExclude(
                        "/druid/**",
                        "/api/user/login",
                        "/api/user/reg",
                        "/api/user/forget",
                        "/api/user/reset",
                        "/api/user/check-email",
                        "/api/user/check-account",
                        "/swagger**",
                        "/swagger-resources/**",
                        "/v2/api-docs",
                        "/picture/**"
                )
                .addExclude("/api/**")
                .setError(new SaFilterErrorStrategy() {
                    @Override
                    public Object run(Throwable e) {
                        return ApiResult.error(401, e.getMessage());
                    }
                })
                .setBeforeAuth(obj -> {
                    // ---------- 设置跨域响应头 ----------
                    SaHolder.getResponse()
                            // 允许指定域访问跨域资源
                            .setHeader("Access-Control-Allow-Origin", "*")
                            // 允许所有请求方式
                            .setHeader("Access-Control-Allow-Methods", "*")

                            // 允许的header参数
                            .setHeader("Access-Control-Allow-Headers", "*");

                    // 如果是预检请求，则立即返回到前端
                    SaRouter.match(SaHttpMethod.OPTIONS)
                            .free(r -> System.out.println("--------OPTIONS预检请求，不做处理"))
                            .back();
                });
    }
}
